//
//  ViewController.swift
//  ParsingCC
//
//  Created by insbridge-macmini1 on 2021/9/1.
//

import UIKit
import SwiftyJSON
import ZipArchive
import IHProgressHUD
//import XMLMapper


class ViewController: UIViewController {
    
    @IBOutlet weak var textview: UITextView!
    
    var musicModel : InsCcMusicModel?;
    var array = [ShmCxMusicModel]();
    
    override func viewDidLoad() {
        super.viewDidLoad();
      
        let musicModel = InsCcMusicModel();
        self.musicModel = musicModel;
//        self.array.removeAll();
//        if let path = Bundle.main.path(forResource: "虫虫数据", ofType: "csv") {
//            if let string = try? String(contentsOfFile: path) {
//                let arr = string.components(separatedBy: "\r\n");
//                for i in 1..<arr.count {
//                    let strArr = arr[i].components(separatedBy: ",");
//                    if strArr.count == 4 {
//                        if strArr[2].count != 0 {
//                            self.array.append(ShmCxMusicModel(songId: strArr[0], songName: strArr[1], songUrl: strArr[2]));
//                        }
//                    }
//                }
//            }
//        }
//        print(self.array.count);
        
        DispatchQueue.global().async {
            _ = ShmDownloadTool.shareInstance;
        }
        
//
        DispatchQueue.global().asyncAfter(deadline: .now() + 3) {
            self.getData();
        }
////        
//    https://s201.lzjoy.com/res/statics/fileupload/ccmz/202212/99/994190-6389fb2006ed2.ccmz
//    https://s201.lzjoy.com/res/statics/fileupload/ccmz/99/cccccc/994190-611396e182254.ccmz
//    https://s201.lzjoy.com/res/statics/fileupload/ccmz/202212/94/942279-639ab3bef30f4.ccmz
//    https://s201.lzjoy.com/res/statics/fileupload/ccmz/94/cccccc/942279-606c11991e2b6.ccmz
//    https://s201.lzjoy.com/res/statics/fileupload/ccmz/202212/99/994125-638a10234c290.ccmz
//    https://s201.lzjoy.com/res/statics/fileupload/ccmz/99/cccccc/994125-61133d1689d13.ccmz
//    "1x5QhUNnQe0","1hLbV9hshHM","score","1x5Qhji8S80","1x5L1O7LILQ","1hLQ4hFyw1g"
//        let fileNames = ["936695"];
//        for fileName in fileNames {
//            if let path = Bundle.main.path(forResource: fileName, ofType: "json") {
//                var tempos = [JSON]();
//                if let path2 = Bundle.main.path(forResource: fileName + "_midi", ofType: "json") {
//                    if let data2 = NSData(contentsOfFile: path2) {
//                        let json = JSON(data2);
//                        tempos = json["tempos"].arrayValue;
//                    }
//                }
//                if let data = NSData(contentsOfFile: path) {
//                    _ = self.musicModel?.makeData(json: JSON(data), fileName: fileName , tempos: tempos);
//                }
//            }
//        }
        

        
        /**
         

         */
        
    }
    
    
    func getData() {
        ShmApiTool.shareInstance.searchMusic(callback: { value in
            if let model = value as? ShmCxMusicModel {
                ShmDownloadTool.shareInstance.downloadMusicFile(model: model) { value in
                    if let (json, mid) = value as? (JSON, JSON) {
                        if let jsonString = json.rawString()?.replacingOccurrences(of: "虫虫", with: "") {
                            let newJson = JSON(parseJSON: jsonString);
                            let tempos = mid["tempos"].arrayValue;
                            _ = self.musicModel?.makeData(json: newJson, fileName: model.songId, tempos: tempos) ?? false;
                            let xmlPath = NSHomeDirectory() + "/Documents/\(model.songId).xml";
                            if let xmlString = try? String(contentsOfFile: xmlPath, encoding: String.Encoding.utf8) {
                                try? FileManager.default.removeItem(atPath: xmlPath);
                                ShmApiTool.shareInstance.getCategorieMusics(musicId: model.songId, xmlString: xmlString) { value in
                                    self.getData();
                                }
                            }else{
                                
                            }
                            return;
                        }
                    }
                    self.getData();
                }
            }else {
                self.getData();
            }
        });
    }
    
    @IBAction func downFile() {
        if self.textview.text.count == 0   {
            return;
        }
        let model = ShmCxMusicModel();
        model.songUrl = self.textview.text;
        model.songId = NSString(string: NSString(string: self.textview.text).lastPathComponent).deletingPathExtension;
        ShmDownloadTool.shareInstance.downloadMusicFile(model: model) { value in
            if let (json, mid) = value as? (JSON, JSON) {
                _ = self.musicModel?.makeData(json: json, fileName: model.songId, tempos: []);
                let xmlPath = NSHomeDirectory() + "/Documents/\(model.songId).xml";
                self.sharePDF(musicPath: xmlPath);
            }
        }
    }
    
    @objc func sharePDF(musicPath : String) {
        IHProgressHUD.show();
        DispatchQueue.main.async {
            let activityViewController = UIActivityViewController(activityItems: [URL(fileURLWithPath: musicPath)], applicationActivities:nil);
//            if IsIpad() {
//                if let window = self.view.window {
//                    activityViewController.popoverPresentationController?.sourceView = window;
//                    activityViewController.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: window.width/5, height: window.height/5);
//                    activityViewController.popoverPresentationController?.permittedArrowDirections  = .any;
//                }
//            }
            self.present(activityViewController, animated: true) {
                IHProgressHUD.dismiss();
            };
        }
    }
    
//
//    func getLoactionData() {
//        if let model = self.array.first {
//            ShmDownloadTool.shareInstance.downloadMusicFile(model: model) { value in
//                if let json = value as? JSON {
//                    if let jsonString = json.rawString()?.replacingOccurrences(of: "虫虫", with: "") {
//                        let newJson = JSON(parseJSON: jsonString);
//                        _ = self.musicModel?.makeData(json: newJson, fileName: model.songId) ?? false;
//                        let xmlPath = NSHomeDirectory() + "/Documents/\(model.songId).xml";
//                        if let xmlString = try? String(contentsOfFile: xmlPath, encoding: String.Encoding.utf8) {
////                            try? FileManager.default.removeItem(atPath: xmlPath);
//                            self.array.removeFirst();
//                            self.getLoactionData();
//                        }
//                        return;
//                    }
//                }
//            }
//        }
//    }
        
}
   
